package system1

import (
	"fmt"
	"strconv"

	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system1"
	system1Req "github.com/flipped-aurora/gin-vue-admin/server/model/system1/request"
	"github.com/flipped-aurora/gin-vue-admin/server/service"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type WorkflowDataApi struct {
}

var WorkflowDataService = service.ServiceGroupApp.System1ServiceGroup.WorkflowDataService

// CreateWorkflowData 创建审批数据
// @Tags WorkflowData
// @Summary 创建审批数据
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system1.WorkflowData true "创建审批数据"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /WorkflowData/createWorkflowData [post]
func (WorkflowDataApi *WorkflowDataApi) CreateWorkflowData(c *gin.Context) {
	var WorkflowData system1.WorkflowData
	err := c.ShouldBindJSON(&WorkflowData)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	WorkflowData.CreatedBy = utils.GetUserID(c)

	if err := WorkflowDataService.CreateWorkflowData(&WorkflowData); err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败", c)
	} else {
		response.OkWithMessage("创建成功", c)
	}
}

// DeleteWorkflowData 删除审批数据
// @Tags WorkflowData
// @Summary 删除审批数据
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system1.WorkflowData true "删除审批数据"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /WorkflowData/deleteWorkflowData [delete]
func (WorkflowDataApi *WorkflowDataApi) DeleteWorkflowData(c *gin.Context) {
	ID := c.Query("ID")
	userID := utils.GetUserID(c)
	if err := WorkflowDataService.DeleteWorkflowData(ID, userID); err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

// DeleteWorkflowDataByIds 批量删除审批数据
// @Tags WorkflowData
// @Summary 批量删除审批数据
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /WorkflowData/deleteWorkflowDataByIds [delete]
func (WorkflowDataApi *WorkflowDataApi) DeleteWorkflowDataByIds(c *gin.Context) {
	IDs := c.QueryArray("IDs[]")
	userID := utils.GetUserID(c)
	if err := WorkflowDataService.DeleteWorkflowDataByIds(IDs, userID); err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败", c)
	} else {
		response.OkWithMessage("批量删除成功", c)
	}
}

// UpdateWorkflowData 更新审批数据
// @Tags WorkflowData
// @Summary 更新审批数据
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system1.WorkflowData true "更新审批数据"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /WorkflowData/updateWorkflowData [put]
func (WorkflowDataApi *WorkflowDataApi) UpdateWorkflowData(c *gin.Context) {
	var WorkflowData system1.WorkflowData
	err := c.ShouldBindJSON(&WorkflowData)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	WorkflowData.UpdatedBy = utils.GetUserID(c)

	if err := WorkflowDataService.UpdateWorkflowData(WorkflowData); err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// FindWorkflowData 用id查询审批数据
// @Tags WorkflowData
// @Summary 用id查询审批数据
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query system1.WorkflowData true "用id查询审批数据"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /WorkflowData/findWorkflowData [get]
func (WorkflowDataApi *WorkflowDataApi) FindWorkflowData(c *gin.Context) {
	ID := c.Query("ID")
	if reWorkflowData, err := WorkflowDataService.GetWorkflowData(ID); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(gin.H{"reWorkflowData": reWorkflowData}, c)
	}
}

// GetWorkflowDataList 分页获取审批数据列表
// @Tags WorkflowData
// @Summary 分页获取审批数据列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query system1Req.WorkflowDataSearch true "分页获取审批数据列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /WorkflowData/getWorkflowDataList [get]
func (WorkflowDataApi *WorkflowDataApi) GetWorkflowDataList(c *gin.Context) {
	var pageInfo system1Req.WorkflowDataSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if list, total, err := WorkflowDataService.GetWorkflowDataInfoList(pageInfo); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.OkWithDetailed(response.PageResult{
			List:     list,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	}
}

/***************************************************************************************
 *start workflow data prepare
 **************************************************************************************/
var DepartmentsService = service.ServiceGroupApp.System1ServiceGroup.Sys_departmentService
var UserService = service.ServiceGroupApp.SystemServiceGroup.UserService

// getDepartments 用parentId查询部门信息Data
// @Tags WorkflowData
// @Summary 用parentId查询部门信息Data
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param parentId query string true "用parentId查询部门信息"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /WorkflowData/getDepartments [get]
func (WorkflowDataApi *WorkflowDataApi) GetDepartments(c *gin.Context) {
	ID := c.Query("parentId")
	if reDeparments, err := DepartmentsService.GetSys_departments_with_employees(ID); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		/*data := make(map[string]interface{})
		 err := json.Unmarshal([]byte(reWorkflow.Flowdata), &data)
		 if err != nil {
			 response.FailWithMessage("查询失败", c)
		 }
		 data["test"] = "asdfasdf"
		 response.OkWithData(gin.H{"data": data}, c)
		*/
		var userList []system.SysUser
		db := global.GVA_DB.Model(&system.SysUser{})
		err = db.Where("department_id = ?", ID).Find(&userList).Error
		if err == nil {
			response.OkWithData(gin.H{"childDepartments": reDeparments, "employees": userList}, c)
		} else {
			response.OkWithData(gin.H{"childDepartments": reDeparments}, c)
		}
	}
}

// getCurrOwners 获取当前审批人
// @Tags WorkflowData
// @Summary 获取当前审批人
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param workflow_data_id query string true "审批数据Id"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /WorkflowData/getCurrOwners [get]
func (WorkflowDataApi *WorkflowDataApi) GetCurrOwners(c *gin.Context) {
	ID := c.Query("workflow_data_id")
	WorkflowData, _ := WorkflowDataService.GetWorkflowData(ID)
	mOnwers, _ := WorkflowDataService.GetCurrentOwners(WorkflowData)
	fmt.Print(mOnwers)
	response.OkWithDetailed(mOnwers, "获取成功", c)
}

// updateCurrOwners 更新当前审批人
// @Tags WorkflowData
// @Summary 更新当前审批人
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param workflow_data_id query string true "审批数据Id"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /WorkflowData/updateCurrOwners [POST]
func (WorkflowDataApi *WorkflowDataApi) UpdateCurrOwners(c *gin.Context) {
	ID := c.Query("workflow_data_id")
	WorkflowData, _ := WorkflowDataService.GetWorkflowData(ID)
	WorkflowDataService.UpdateCurrentOwners(WorkflowData)
	response.OkWithDetailed("", "更新成功", c)
}

// approve 审批人通过审批
// @Tags WorkflowData
// @Summary 审批人通过审批
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param workflow_data_id query string true "审批数据Id"
// @Param comment query string true "备注"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"操作成功"}"
// @Router /WorkflowData/approve [post]
func (WorkflowDataApi *WorkflowDataApi) Approve(c *gin.Context) {
	ID := c.Query("workflow_data_id")
	mComment := c.Query("comment")
	userId := utils.GetUserID(c)

	WorkflowDataPrev, _ := WorkflowDataService.GetWorkflowData(ID)
	mOnwers, _ := WorkflowDataService.GetCurrentOwners(WorkflowDataPrev)
	fmt.Print(mOnwers)
	WorkflowDataService.WorkflowDataApprove(WorkflowDataPrev, mComment, userId)

	//get flow after approved or rejected
	WorkflowData, _ := WorkflowDataService.GetWorkflowData(ID)
	WorkflowDataService.UpdateCurrentOwners(WorkflowData)
	currOWner, _ := WorkflowDataService.GetCurrentOwners(WorkflowData)
	//when currOwners is nil means the process end. current action is final result
	if currOWner == nil {
		WorkflowData.State = "approved"
		WorkflowDataService.UpdateWorkflowData(WorkflowData)
	}
	WorkflowLogService.AddWorkflowLog(utils.GetUserID(c), ID, "approved", mComment)
}

// reject 审批人驳回审批
// @Tags WorkflowData
// @Summary 审批人驳回审批
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param workflow_data_id query string true "审批数据Id"
// @Param comment query string true "备注"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"操作成功"}"
// @Router /WorkflowData/reject [post]
func (WorkflowDataApi *WorkflowDataApi) Reject(c *gin.Context) {
	ID := c.Query("workflow_data_id")
	mComment := c.Query("comment")
	userId := utils.GetUserID(c)

	WorkflowDataPrev, _ := WorkflowDataService.GetWorkflowData(ID)
	mOnwers, _ := WorkflowDataService.GetCurrentOwners(WorkflowDataPrev)
	WorkflowDataService.WorkflowDataReject(WorkflowDataPrev, mComment, userId)
	fmt.Print(mOnwers)

	//get flow after approved or rejected
	WorkflowData, _ := WorkflowDataService.GetWorkflowData(ID)
	WorkflowDataService.UpdateCurrentOwners(WorkflowData)
	currOWner, _ := WorkflowDataService.GetCurrentOwners(WorkflowData)
	//when currOwners is nil means the process end. current action is final result
	if currOWner == nil {
		WorkflowData.State = "rejected"
		WorkflowDataService.UpdateWorkflowData(WorkflowData)
	}
	WorkflowLogService.AddWorkflowLog(utils.GetUserID(c), ID, "rejected", mComment)
}

// createApplication 提交审批申请
// @Tags WorkflowData
// @Summary 提交审批申请
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param workflow_def_id query string true "审批Def_Id"
// @Param title query string true "申请标题"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"操作成功"}"
// @Router /WorkflowData/createApplication [post]
func (WorkflowDataApi *WorkflowDataApi) CreateApplication(c *gin.Context) {
	userService := service.ServiceGroupApp.SystemServiceGroup.UserService

	wfDefIdStr := c.Query("workflow_def_id")
	wfDefId, _ := strconv.Atoi(wfDefIdStr)
	title := c.Query("title")
	userId := utils.GetUserID(c)
	uuid := utils.GetUserUuid(c)
	userInfo, _ := userService.GetUserInfo(uuid)

	WorkflowDef, _ := WorkflowDefService.GetWorkflowDef(wfDefIdStr)

	var WorkflowData system1.WorkflowData
	WorkflowData.State = "running"
	WorkflowData.Title = title
	WorkflowData.CreatedBy = userId
	WorkflowData.SubmitterId = int(userId)
	WorkflowData.SubmitterDepartmentId = userInfo.DepartmentId
	WorkflowData.WorkflowdefId = wfDefId
	WorkflowData.WorkflowdefName = WorkflowDef.Name
	WorkflowData.Flow = WorkflowDef.Flowdata

	err := WorkflowDataService.CreateWorkflowData(&WorkflowData)
	if err == nil {
		WorkflowDataService.UpdateCurrentOwners(WorkflowData)
		response.OkWithDetailed("", "操作成功", c)
	} else {
		response.FailWithDetailed("", "操作失败", c)

	}
}
